<template>
  <div>
    <el-form>
      <el-form-item label="角色名称">
        <el-input v-model="role.name" />
      </el-form-item>
      <el-form-item label="角色编码">
        <el-input v-model="role.code" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input
          v-model="role.description"
          type="textarea"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="$emit('cancel')">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit"
        >
          确认
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, ref } from 'vue'
import { createOrUpdate, getRoleById } from '/@/services/role'
import { ElMessage } from 'element-plus'
const role = ref({})
const useInit = (props: any) => {
  role.value = {
    code: '',
    name: '',
    description: ''
  }
  const loadRoleById = async (id: number) => {
    const { data } = await getRoleById(id)
    role.value = data.data
  }
  onBeforeMount(() => {
    if (props.isEdit) {
      loadRoleById(props.roleId)
    }
  })
  return {
    role,
    loadRoleById
  }
}
export default defineComponent({
  name: 'CreateOrEditRole',
  props: {
    roleId: {
      type: [String, Number],
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  emits: ['success', 'cancel'],
  setup (props, { emit }) {
    const onSubmit = async () => {
      await createOrUpdate(role.value)
      ElMessage.success('操作成功')
      emit('success')
    }
    return {
      onSubmit,
      ...useInit(props)
    }
  }
})
</script>

<style lang="scss" scoped></style>
